package com.cspm.common.util;


import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 获取指定URL的数据
 * 
 * @author CHENQUAN
 * @date 2016年9月13日
 */
public class GetUrlUtil {
    /**
     * 建立连接，并获取网页内容
     * 
     * @param urlString
     *            链接地址
     * @param context
     *            post请求正文
     * @return 返回的String
     * @throws MalformedURLException
     * @throws ConnectException
     * @throws IOException
     */
    public static String getUrlConnectionToString(String urlString,
                                                  String context, String requestMethod) throws MalformedURLException,
            ConnectException, IOException {
	String returnMessage = null;
	HttpURLConnection http = null;
	URL url = new URL(urlString);
	http = (HttpURLConnection) url.openConnection();
	http.setRequestMethod(requestMethod);
	http.setRequestProperty("Content-Type",
		"application/x-www-form-urlencoded");
	http.setDoOutput(true);
	http.setDoInput(true);
	http.setConnectTimeout(30000);
	http.setReadTimeout(30000);
	http.connect();
	if (context != null && !"".equals(context)) {
	    OutputStream os = http.getOutputStream();
	    os.write(context.getBytes("UTF-8"));
	    os.flush();
	    os.close();
	}
	InputStream is = http.getInputStream();
	returnMessage = readInputStream(is);
	return returnMessage;
    }

    /**
     * 建立连接，并获取网页内容，转为JSON
     * 
     * @param urlString
     *            链接地址
     * @param context
     *            post请求正文
     * @return 返回的JSONObject
     * @throws MalformedURLException
     * @throws ConnectException
     * @throws IOException
     */
    public static JSONObject getUrlConnection(String urlString, String context,
											  String requestMethod) throws MalformedURLException,
            ConnectException, IOException {
	JSONObject json = new JSONObject();
	HttpURLConnection http = null;

	URL url = new URL(urlString);
	http = (HttpURLConnection) url.openConnection();
	http.setRequestMethod(requestMethod);
	http.setRequestProperty("Content-Type",
		"application/x-www-form-urlencoded");
	http.setDoOutput(true);
	http.setDoInput(true);
	http.setConnectTimeout(30000);
	http.setReadTimeout(30000);
	http.connect();
	if (context != null && !"".equals(context)) {
	    OutputStream os = http.getOutputStream();
	    os.write(context.getBytes("UTF-8"));
	    os.flush();
	    os.close();
	}
	InputStream is = http.getInputStream();
	String returnMessage = readInputStream(is);
	json = (JSONObject) JSONObject.toJSON(returnMessage);
	http.disconnect();
	return json;
    }

    /**
     * 读取输入流转成格式为utf-8的字符串
     * 
     * @version 2015年12月24日
     * @param in
     *            字符输入流
     * @return 字符串
     */
    public static String readInputStream(InputStream in) {
	// System.out.println("读取输入流开始");
	StringBuffer buffer = new StringBuffer();
	BufferedReader reader = null;
	InputStreamReader isr = null;
	try {
	    isr = new InputStreamReader(in, "UTF-8");
	    reader = new BufferedReader(isr);
	    String line = null;
	    while ((line = reader.readLine()) != null) {
		buffer.append(line);
	    }
	    // System.out.println("读取完成" + buffer.toString());
	} catch (IOException e) {
	    e.printStackTrace();
	    System.out.println("读取异常" + e.getMessage());
	} finally {
	    try {
		if (isr != null) {
		    isr.close();
		    // System.out.println("关闭isr");
		}
		if (reader != null) {
		    reader.close();
		    // System.out.println("关闭reader");
		}
	    } catch (IOException e) {
		e.printStackTrace();
		System.out.println("关闭输入流异常" + e.getMessage());
	    }
	}
	return buffer.toString();
    }
}